package cn.nucun.factory;

import cn.nucun.base.WindowsRem;
import cn.nucun.frame.MainCreateFrame;
import cn.nucun.utils.PlugsUtils;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowFactory;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import org.jetbrains.annotations.NotNull;

/**
 * 工作框
 *
 * @author chen
 * @date 2020-12-21
 */
public class ToolWindowsFactory implements ToolWindowFactory, Condition<Project> {

    /**
     * 创建 toolWindow
     *
     * @param project    调用方数据
     * @param toolWindow 框
     */
    @Override
    public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) {
        MainCreateFrame mainCreateFrame = new MainCreateFrame();
        ContentFactory contentFactory = ContentFactory.SERVICE.getInstance();
        Content content = contentFactory.createContent(mainCreateFrame.getPanel(), null, false);
        toolWindow.getContentManager().addContent(content);
    }

    /**
     * 控制tool window是否展示
     *
     * @param project 数据
     * @return true展示  false不展示
     */
    @Override
    public boolean value(Project project) {
        return PlugsUtils.checkLogin();
    }

    @Override
    public boolean isApplicable(@NotNull Project project) {
        WindowsRem.PRO = project;
        return true;
    }

    @Override
    public void init(@NotNull ToolWindow toolWindow) {
        WindowsRem.TW = toolWindow;
    }

    /**
     * 重新打开当前对象
     */
    public void reOpen() {
        if (WindowsRem.TW != null) {
            WindowsRem.TW.getContentManager().removeAllContents(true);
            createToolWindowContent(WindowsRem.PRO,WindowsRem.TW);
            WindowsRem.TW.show();
        }
    }

    /**
     * 打开一个新的窗体
     */
    public void newOne() {
        if (WindowsRem.TW != null) {
            createToolWindowContent(WindowsRem.PRO,WindowsRem.TW);
            WindowsRem.TW.show();
        }
    }

    /**
     * 关闭
     */
    public void tryClose() {
        if (WindowsRem.TW != null) {
            WindowsRem.TW.isAvailable();
            WindowsRem.TW.hide();
        }
    }

    /**
     * 去除
     */
    public void tryRemove() {
        if (WindowsRem.TW != null) {
            WindowsRem.TW.remove();
        }
    }
}